import TileMap from './TileMap';
import Const from '../../common/const';
import Utils from '../../common/Utils';

export default class TileSetTileMap extends TileMap {

    async setConfig(opt) {
        await super.setConfig(undefined);
        if (opt == null) {
            return;
        }

        let config = this.config || {
            name: '未命名图块集',
            tileWidth: Const.TileWidth,
            tileHeight: Const.TileHeight,
            width: Const.PaletteTileCountPerLine,
            height: Const.DefaultMapHeight,
            type: 'tileset',
            materials: [],
            cells: []
        };
        Utils.minerAssign(config, opt);
        await this.loadMaterial(config);
        this.initCells(config);
        this.opt = opt;
        this.config = config;
    }

    initCells(config) {
        let cells = [];
        config.materials.forEach((res, resIndex) => {
            if (Reflect.getPrototypeOf(res) == null || Reflect.getPrototypeOf(res) == Object.prototype) {
                throw new Error('Material not loaded: ' + JSON.stringify(res));
            }
            let startHeight = cells.length;
            for (let sx = 0; sx * res.tileWidth < res.imageWidth; sx += config.width) {
                for (let y = 0; y * res.tileHeight < res.imageHeight; ++y) {
                    cells.push(
                        Array.range(sx, sx + config.width)
                        .map(x => ({
                            pos: [x - sx, cells.length],
                            tiles: [{
                                src: [x, y],
                                res: resIndex
                            }]
                        }))
                    );
                }
            }
            let stopHeight = cells.length;
            res.editor = {
                startHeight,
                stopHeight,
                height: stopHeight - startHeight
            };
        });
        config.height = cells.length;
        config.cells = cells;
    }
}
